package com.yun.util.yun.utils.string;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

    /**
     * <p>Method: stringTrimString </p>
     * <p>Description: 去掉传入的String参数的空格</p>
     */
    public static String stringTrimString(String s) {
        if (null != s && !"".equals(s)) {
            if (s.equals("null")) {
                return "";
            } else {
                return s.trim();
            }
        } else {
            return "";
        }

    }

    /**
     * <p>Method: stringTrimAndTrans </p>
     * <p>Description: 去掉传入的String参数的空格</p>
     */
    public static String stringTrimAndTrans(String s) {
        if (null != s && !"".equals(s)) {
            if (s.equals("null")) {
                return "";
            } else {
                /* */
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    switch (c) {
                        case '\"':
                            sb.append("\\\"");
                            break;
                        case '\\':
                            sb.append("\\\\");
                            break;
                        case '/':
                            sb.append("\\/");
                            break;
                        case '\b':
                            sb.append("\\b");
                            break;
                        case '\f':
                            sb.append("\\f");
                            break;
                        case '\n':
                            sb.append("\\n");
                            break;
                        case '\r':
                            sb.append("\\r");
                            break;
                        case '\t':
                            sb.append("\\t");
                            break;
                        default:
                            sb.append(c);
                    }
                }
                return sb.toString().trim();
            }
        } else {
            return "";
        }

    }

    /**
     * <p>Method: getSqlErrorMess </p>
     * <p>Description: 截取sql异常信息</p>
     */
    public static String getSqlErrorMess(String s) {
        int start = s.indexOf(":");
        int end = s.indexOf("\n");
        if (start != -1 && end != -1 && end > start) {
            return s.substring(start + 1, end);
        } else {
            return s;
        }

    }

    /**
     * <p>Method:decodeAndTrim  </p>
     * <p>Description:去掉传入的String参数的空格,并转换为UTF-8格式 </p>
     */
    public static String decodeAndTrim(String s) {
        String ss = "";
        if (null != s && !"".equals(s)) {
            try {
                ss = java.net.URLDecoder.decode(s.trim(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            return "";
        }
        return ss;
    }

    /**
     * <p>Method: stringSubString </p>
     * <p>Description:去掉传入的String参数的空格 </p>
     */
    public static String stringSubString(String s) {
        if (null != s && !"".equals(s)) {
            if (s.equals("null")) {
                return "";
            } else {
                if (s.contains("-")) {
                    return s.trim().substring(0, s.trim().indexOf("-"));
                } else {
                    return s.trim();
                }
            }
        } else {
            return "";
        }

    }

    /**
     * <p>Method: SubTimeString </p>
     * <p>Description:从Excel中导入Ip备案的时候对日期进行处理，如果日期格式是 2004-06-10 00:00:00.0
     * 这中格式的则将00:00:00.0截取掉 </p>
     */
    public static String SubTimeString(String s) {
        if (null != s && !"".equals(s)) {
            if (s.equals("null")) {
                return "";
            } else {
                if (s.contains("-")) {
                    if (s.endsWith("00:00:00.0")) {
                        return s.trim().substring(0, s.length() - 10).trim();
                    } else {
                        return s.trim();
                    }
                } else {
                    return "";
                }

            }
        } else {
            return "";
        }

    }

    /**
     * <p>Method:  </p>
     * <p>Description:导入蓄电池续航时间的时候对续航时间是">=100"的格式进行处理 </p>
     */
    public static String subSting2(String s) {
        if (null != s && !"".equals(s)) {
            if (s.equals("null")) {
                return "";
            } else {
                if (s.contains(">=")) {
                    return s.trim().substring(2, s.length());
                } else {
                    return s.trim();
                }

            }
        } else {
            return "";
        }

    }

    /**
     * <p>Method:  </p>
     * <p>Description: 获取IP地址的方法</p>
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static int getSubStrCount(String str, String subStr) {
        int count = 0;
        int start = 0;
        while (str.indexOf(subStr, start) > 0 && start < str.length()) {
            count++;
            start = str.indexOf(subStr, start) + subStr.length();
        }
        return count;

    }

    /**
     * <p>Method: isContainChinese </p>
     * <p>Description: 判断字符串是否包含中文</p>
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * <p>Method:  </p>
     * <p>Description: ORACLE分页查询sql</p>
     * <p>pageSize(一页显示的条数)</p>
     * <p>offset(从第几条开始)</p>
     * <p>@param sql(未分页的sql)</p>
     */
    public static String oraclePage(int pageSize, int offset, String sql) {
        String rtSql = "SELECT * FROM (SELECT PA.*,ROWNUM ROWN FROM (" + sql
                + ") PA WHERE ROWNUM <=" + (pageSize + offset)
                + ") WHERE ROWN > " + offset;
        return rtSql;
    }

    /**
     * <p>Method:  </p>
     * <p>Description:获取sql查询结果的count值 </p>
     */
    public static String sqlCount(String sql) {
        String rtCount = "SELECT COUNT(*) FROM (" + sql + ")";
        return rtCount;
    }

    /**
     * <p>Method:  </p>
     * <p>Description: 获取Quartz 的 Cron 表达式</p>
     * <p>exeCycle 0:月 1:周 2:日 </p>
     * <p>cycleValue 设定值 </p>
     */
    public static String getCornStr(String exeCycle, String cycleValue, String exeTime) {
        String timer = "";
        String[] timesS = exeTime.split(":");
        String hour = timesS[0];
        String min = timesS[1];
        if (min.equals("00")) {
            min = "0";
        }
        if (exeCycle.equals("0")) {//设定的执行周期为月
            timer = "0 " + min + " " + hour + " " + cycleValue + " * ?";
        } else if (exeCycle.equals("1")) {//设定的执行周期为周
            timer = "0 " + min + " " + hour + " ? * " + cycleValue;
        } else if (exeCycle.equals("2")) {//设定的执行周期为日
            timer = "0 " + min + " " + hour + " * * ?";
        } else {//设定的执行周期为仅一次
            String[] dates = exeTime.split("-");
            timer = "0 " + min + " " + hour.split(" ")[1] + " " + Integer.parseInt(dates[2].split(" ")[0]) + " " + Integer.parseInt(dates[1]) + " ? " + dates[0];
        }
        return timer;
    }

    /**
     * <p>Method:  </p>
     * <p>Description: 通过corn表达式拆分成界面可识别的</p>
     */
    public static Map<String, String> getStrFormCorn(String expression) {
        String[] exp = expression.split(" ");
        String exeTime = exp[2] + ":" + exp[1];
        String exeCycle = "";
        String cycVal = "";
        if (exp[4].equals("*") && exp[5].equals("?")) {
            exeCycle = "0";
            cycVal = exp[3];
        }
        if (exp[3].equals("?") && exp[4].equals("*")) {
            exeCycle = "1";
            cycVal = exp[5];
        }
        if (exp[3].equals("*") && exp[4].equals("*") && exp[5].equals("?")) {
            exeCycle = "2";
        }
        Map<String, String> map = new HashMap<>();
        map.put("exeCycle", exeCycle);
        map.put("cycVal", cycVal);
        map.put("exeTime", exeTime);
        return map;
    }

    public static JSONArray getCycleValue(String cycleType) {
        JSONArray rtJa = new JSONArray();
        JSONObject jso = new JSONObject();
        if (cycleType.equals("0")) {
            jso.put("id", "L");
            jso.put("text", "每月最后一天");
            rtJa.add(jso);
            for (int i = 1; i <= 31; i++) {
                jso = new JSONObject();
                jso.put("id", i + "");
                jso.put("text", i + "号");
                rtJa.add(jso);
            }
        } else if (cycleType.equals("1")) {
            jso.put("id", "2");
            jso.put("text", "周一");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "3");
            jso.put("text", "周二");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "4");
            jso.put("text", "周三");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "5");
            jso.put("text", "周四");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "6");
            jso.put("text", "周五");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "7");
            jso.put("text", "周六");
            rtJa.add(jso);
            jso = new JSONObject();
            jso.put("id", "1");
            jso.put("text", "周日");
            rtJa.add(jso);
        } else {
            rtJa.add(jso);
        }
        return rtJa;
    }

    public static String getSuperCondition(JSONArray conditionJa) {
        String conditions = "";
        if(conditionJa==null){
            conditionJa = new JSONArray();
        }
        for (int i = 0; i < conditionJa.size(); i++) {
            JSONObject jo = conditionJa.getJSONObject(i);
            if (jo.size() == 0) {
                continue;
            } else {
                String value = jo.getString("value");
                if (!value.equals("")) {
                    if (value.startsWith("%") || value.endsWith("%")) {
                        conditions += " AND " + jo.getString("name").replace("find_", "") + " LIKE '" + jo.getString("value") + "' ";
                    } else {
                        if (jo.getString("name").replace("find_", "").equals("INAS_IMPORT_TIME")) {
                            conditions += " AND  TO_CHAR(INAS_IMPORT_TIME,'YYYY-MM-DD') = '" + jo.getString("value") + "'";
                        } else {
                            conditions += " AND " + jo.getString("name").replace("find_", "") + " = '" + jo.getString("value") + "' ";
                        }
                    }
                }
            }
        }
        return conditions;
    }

    public static String getSuperCondition(JSONObject conditionJa) {
        String conditions = "";
        for (Map.Entry<String, Object> entry : conditionJa.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue() + "";
            if (value.startsWith("%") || value.endsWith("%")) {
                conditions += " AND " + key + " LIKE '" + value + "' ";
            } else {
                if (key.equals("INAS_IMPORT_TIME")) {
                    conditions += " AND TO_CHAR(INAS_IMPORT_TIME,'YYYY-MM-DD') = '" + value + "' ";
                } else {
                    conditions += " AND " + key + " = '" + value + "' ";
                }
            }
        }
        return conditions;
    }

    public static String getParamWhereSql(String superSearchParams, JSONArray superForm) {
        String whereSql = "";
        if (superSearchParams != null) {
            JSONObject params = JSONObject.parseObject(superSearchParams);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue() + "";
                if (params.getString(key).startsWith("%") || params.getString(key).endsWith("%")) {
                    whereSql += " AND " + key + " LIKE '" + params.getString(key) + "' ";
                } else {
                    if (key.equals("INAS_IMPORT_TIME")) {
                        whereSql += " AND TO_CHAR(INAS_IMPORT_TIME,'YYYY-MM-DD') = '" + params.getString(key) + "' ";
                    } else {
                        whereSql += " AND " + key + " = '" + params.getString(key) + "' ";
                    }
                }
            }
        } else {
            whereSql += getSuperCondition(superForm);
        }
        return whereSql;
    }

    public static JSON getResultTableData(JSONObject result) {
        JSONObject rtObj = new JSONObject();
        if (result.getBoolean("success")) {
            if (result.getString("message").startsWith("[")) {
                return result.getJSONArray("message");
            } else {
                rtObj.put("rows", result.getJSONObject("message").getJSONArray("contexts"));
                rtObj.put("total", result.getJSONObject("message").getInteger("totalElements"));
            }
        }
        return rtObj;
    }

    
}
